{% extends '::base.html.twig' %}
{% form_theme form 'WantuchMailerBundle:Main/Form:fields.html.twig' %}

{% block title %}{{ "Wyślij wiadomość w kampanii" | trans}} {{campaign.name}}{% endblock %}
 
{% block body %}
    
    {% block content %}
    <h1 class="heading">Wyślij wiadomość w kampanii {{campaign.name}}</h1>

    {{ form_start(form) }}
        {{ form_errors(form) }}
    
        {{ form_row(form.title) }}
        {{ form_row(form.sender) }}
        
        <div class="form-group">
            <label>Odbiorcy przypisani do kampanii ({{campaign.subscribers|length}})</label>
                <div class="form-control receivers-list" id="exampleInputEmail1">
                  {% for subscriber in campaign.subscribers %}
                       <div class="single">{{subscriber.email}}</div>
                  {% endfor %}
                  
                  <div class="single not-email">i <b>33</b> więcej<span class="more">»</span></div>
                </div>
        </div>
        {{ form_row(form.additionalReceivers) }}
        {{ form_row(form.csvFile) }}<a href="#" class="loadCsv" style="display:none;">Kliknij, żeby załadować</a>
        <div class="form-group" id="additional-receivers" style="display:none">
            <label>Odbiorcy z pliku CSV</label>
                <div class="form-control" id="editor">
                  
                  
                  
                </div>
        </div>
        {{ form_row(form.content) }}
        {{ form_row(form.attachments) }}
        <div class="form-group additionalAttachmentsWrapper">
            
        </div>
            
        
        
        <div class="fileList"></div>
        {{ form_widget(form.save) }}
    {{ form_end(form) }}
{%endblock%}
{%endblock%}

{% block javascripts %}
    {{ parent() }}
    
    <script type="text/javascript">
    $(document).ready(function(){
    
  });
  </script>
    
<script type="text/javascript">
    tinymce.init({
            selector: "#form_content",
            plugins: [
                    "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
                    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                    "table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker textpattern"
            ],

            toolbar1: "newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
            toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | insertdatetime preview | forecolor backcolor",
            toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",

            menubar: false,
            toolbar_items_size: 'small',

            style_formats: [
                    {title: 'Bold text', inline: 'b'},
                    {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
                    {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
                    {title: 'Example 1', inline: 'span', classes: 'example1'},
                    {title: 'Example 2', inline: 'span', classes: 'example2'},
                    {title: 'Table styles'},
                    {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
            ],

            templates: [
                    {title: 'Test template 1', content: 'Test 1'},
                    {title: 'Test template 2', content: 'Test 2'}
            ]
    });
 </script>
 
 <script>        
        function handleFiles(files) {
            // Check for the various File API support.
            if (window.FileReader) {
                // FileReader are supported.
                getAsText(files[0]);
            } else {
                alert('FileReader are not supported in this browser.');
            }
        }

        function getAsText(fileToRead) {
            var reader = new FileReader();
            // Read file into memory as UTF-8      
            reader.readAsText(fileToRead);
            // Handle errors load
            reader.onload = loadHandler;
            reader.onerror = errorHandler;
        }

        function loadHandler(event) {
            var csv = event.target.result;
            processData(csv);
        }

        function processData(csv) {
            var allTextLines = csv.split(/\r\n|\n/);
            var lines = [];
            for (var i=0; i<allTextLines.length-1; i++) {
                var data = allTextLines[i].split(';');
                    var tarr = [];
                    for (var j=0; j<data.length; j++) {
                        tarr.push(data[j]);
                    } 
                    //document.getElementById('editor').appendChild(document.createTextNode(tarr[2]+"\n"));
                    $("#editor").append(tarr[2]+"<br />");
                    lines.push(tarr);
            }
            console.log(lines);
        }

        function errorHandler(evt) {
            if(evt.target.error.name == "NotReadableError") {
                alert("Canno't read file !");
            }
        }


    $( "#form_csvFile" ).change(function() {
        $("#editor").html("");
        $("#additional-receivers").show();
         handleFiles(document.getElementById('form_csvFile').files);  
    });
    
    var pullfiles=function(){ 
       // love the query selector
       $("#form_attachments").hide();
       var fileInput = document.querySelector("#form_attachments");
       var files = fileInput.files;
       // cache files.length 
       var fl=files.length;
       var i=0;

       while ( i < fl) {
           // localize file var in the loop
           var file = files[i];
           if(file.size<1024*1024){
               var fsize=(file.size/1024).toPrecision(3)+" KB";
           }else{
               var fsize=(file.size/1024/1024).toPrecision(3)+" MB";
           }
           $(".fileList").append(file.name+" Rozmiar: "+fsize+"<br />");
           i++;
       }    
       var newinput="<input type=\"file\" multiple=\"multiple\" name=\"form[attachments][]\" class=\"additionalAttachments form-control\">";
        $('.additionalAttachmentsWrapper').append(newinput);
        
   };

   // set the input element onchange to call pullfiles
   document.querySelector("#form_attachments").onchange=pullfiles;
   
   

   //a.t
   $(".additionalAttachments").change(function(e) {
        $(this).hide();
        var fileInput = this;
        var files = fileInput.files;
        var fl=files.length;
        var i=0;

        while ( i < fl) {
           var file = files[i];
           if(file.size<1024*1024){
               var fsize=(file.size/1024).toPrecision(3)+" KB";
           }else{
               var fsize=(file.size/1024/1024).toPrecision(3)+" MB";
           }
           $(".fileList").append(file.name+" Rozmiar: "+fsize+"<br />");
           i++;
        }
        var el = $('<input type="file" id="test1" multiple="multiple" name="form[attachments][]" class="additionalAttachments form-control">');

        $(".additionalAttachmentsWrapper").append(el);

        //$("#test1").change(function(e) {
        //    alert("alert z dynamicznego");
        //});
        //var newinput="<input type=\"file\" multiple=\"multiple\" name=\"form[attachments][]\" class=\"additionalAttachments form-control\">";
        //$('.additionalAttachmentsWrapper').append(newinput);
    });
    
    var addInput=function(){ 
        $(this).hide();
        var fileInput = this;
        var files = fileInput.files;
        var fl=files.length;
        var i=0;

        while ( i < fl) {
           var file = files[i];
           if(file.size<1024*1024){
               var fsize=(file.size/1024).toPrecision(3)+" KB";
           }else{
               var fsize=(file.size/1024/1024).toPrecision(3)+" MB";
           }
           $(".fileList").append(file.name+" Rozmiar: "+fsize+"<br />");
           i++;
        }
        
        var el = $('<input type="file" multiple="multiple" name="form[attachments][]" class="additionalAttachments form-control">');

        $(".additionalAttachmentsWrapper").append(el);

        //el.change(addInput);

        //var newinput="<input type=\"file\" multiple=\"multiple\" name=\"form[attachments][]\" class=\"additionalAttachments form-control\">";
        //$('.additionalAttachmentsWrapper').append(newinput);
    };
    $("form").on("change", ".additionalAttachments", addInput);
    </script>

    {%endblock%}